from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin, AnonymousUserMixin
from . import login_manager, db
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from flask import current_app, request
from datetime import datetime
import hashlib
from markdown import markdown
import bleach
from bs4 import BeautifulSoup
from jieba.analyse.analyzer import ChineseAnalyzer


class Role(db.Model):
    __tablename__ = 'roles'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    default = db.Column(db.Boolean, default=False, index=True)
    permissions = db.Column(db.Integer)
    users = db.relationship('User', backref='role', lazy='dynamic')

    @staticmethod
    def insert_roles():
        roles = {
            'User': (Permission.FOLLOW |
                     Permission.COMMIT |
                     Permission.WRITE_ARITCLES, True
                     ),
            'Moderator': (Permission.FOLLOW |
                          Permission.COMMIT |
                          Permission.WRITE_ARITCLES |
                          Permission.MODERATE_COMMENTS, False
                          ),
            'Administrator': (0xff, False)
        }
        for r in roles:
            role = Role.query.filter_by(name=r).first()
            if role is None:
                role = Role(name=r)  # 不创建新的字段，从数据库读取，然后根据上面定义的，依次赋值提交
            role.permissions = roles[r][0]
            role.default = roles[r][1]
            db.session.add(role)
        db.session.commit()

    def __repr__(self):
        return '<Role %r>' % self.name


class Follow(db.Model):
    __tablename__ = 'follows'
    follower_id = db.Column(  # 关注者 粉丝
        db.Integer, db.ForeignKey('users.id'), primary_key=True)
    followed_id = db.Column(  # 被关注者 up主
        db.Integer, db.ForeignKey('users.id'), primary_key=True)
    timestamp = db.Column(db.DateTime, default=datetime.utcnow)


class User(UserMixin, db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(64), unique=True, index=True)
    username = db.Column(db.String(64), unique=True, index=True)
    password_hash = db.Column(db.String(128))
    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
    confirmed = db.Column(db.Boolean, default=False)  # default 打错了。
    name = db.Column(db.String(64))
    location = db.Column(db.String(64))
    about_me = db.Column(db.Text())
    member_since = db.Column(db.DateTime(), default=datetime.utcnow)
    last_seen = db.Column(db.DateTime(), default=datetime.utcnow)
    avatar_hash = db.Column(db.String(32))
    posts = db.relationship('Post', backref='author', lazy='dynamic')
    post_types = db.relationship('PostType', backref='user', lazy='dynamic')
    # 这个follow 类必须要放到这个类前面，不然不会提示
    followed = db.relationship('Follow', foreign_keys=[Follow.follower_id],
                               backref=db.backref('follower', lazy='joined'),
                               lazy='dynamic', cascade='all,delete-orphan')
    followers = db.relationship('Follow', foreign_keys=[Follow.followed_id],
                                backref=db.backref('followed', lazy='joined'),
                                lazy='dynamic', cascade='all,delete-orphan')

    def __repr__(self):
        return '<User %r>' % self.username

    def __init__(self, **kwargs):
        super(User, self).__init__(**kwargs)
        if self.role is None:
            self.role = Role.query.filter_by(default=True).first()  # 默认
            if self.email == current_app.config['FLASKY_ADMIN']:
                self.role = Role.query.filter_by(
                    permission=0xff).first()  # 如果邮箱为后台设置的，则可以设置为网站管理员
        if self.email is not None and self.avatar_hash is None:
            self.avatar_hash = hashlib.md5(
                self.email.encode('utf-8')).hexdigest()

    def follow(self, user):  # 关注
        if not self.is_following(user):
            f = Follow(follower=self, followed=user)
            db.session.add(f)

    def unfollow(self, user):  # 取关
        f = self.followed.filter_by(
            followed_id=user.id).first()  # 取出来我关注的这个人，如果关注了，就取关
        if f:
            db.session.delete(f)

    def is_following(self, user):  # 是否关注了这个用户
        return self.followed.filter_by(followed_id=user.id).first() is not None

    def is_following_by(self, user):  # 是否关注了我
        return self.followers.filter_by(follower_id=user.id).first() is not None

    def change_email(self, token):
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except:
            return False
        if data.get('change_email') != self.id:
            return False
        new_email = data.get('new_email')
        if new_email is None:
            return False
        if self.query.filter_by(email=new_email).first() is not None:
            return False
        self.email = new_email
        self.avatar_hash = hashlib.md5(
            self.email.encode('utf-8')).hexdigest()
        db.session.add(self)
        return True

    def ping(self):
        self.last_seen = datetime.utcnow()
        db.session.add(self)

    def gravatar(self, size=100, default='identicon', rating='g'):  # 随机生成的一张头像
        if request.is_secure:
            url = 'https://secure.gravatar.com/avatar'
        else:
            url = 'http://www.gravatar.com/avatar'
        # 把 邮箱转换为 md5 唯一的，因为邮箱也是唯一的
        hash = self.avatar_hash or hashlib.md5(
            self.email.encode('utf-8')).hexdigest()  # 根据邮箱生成的
        return f'{url}/{hash}?s={size}&d={default}&r={rating}'

    @property
    def password(self):
        raise AttributeError('password is not a readable attribute')

    @password.setter  # password 设置器
    def password(self, password):
        self.password_hash = generate_password_hash(
            password)  # 调用函数保存密码的哈希值到数据库

    def generate_confirmation_token(self, expiration=3600):  # 生成验证token
        s = Serializer(current_app.config['SECRET_KEY'], expiration)
        return s.dumps({'confirm': self.id})

    def can(self, permissions):
        return self.role is not None and (self.role.permissions & permissions) == permissions

    def is_administrator(self):
        return self.can(Permission.ADMINISTER)

    def confirm(self, token):
        # 实例化，有加密钥匙就行了，不需要时间参数
        s = Serializer(current_app.config['SECRET_KEY'])
        try:  # 尝试获取 data
            data = s.loads(token)
        except:
            return False
        if data.get('confirm') != self.id:  # 获取data的'confirm' ,如果和id不一样，就返回false
            return False
        self.confirmed = True
        db.session.add(self)
        return True

    def verify_password(self, password):
        # 返回布尔值 检查密码是否正确
        return check_password_hash(self.password_hash, password)

    @staticmethod
    def genrate_fake(count=100):
        from sqlalchemy.exc import IntegrityError
        from random import seed
        import forgery_py

        seed()
        for i in range(count):
            u = User(email=forgery_py.internet.email_address(),
                     username=forgery_py.internet.user_name(True),
                     password=forgery_py.lorem_ipsum.word(),
                     confirmed=True,
                     name=forgery_py.name.full_name(),
                     location=forgery_py.address.city(),
                     about_me=forgery_py.lorem_ipsum.sentence(),
                     member_since=forgery_py.date.date(True)
                     )
            db.session.add(u)
            try:
                db.session.commit()  # 尝试提交
            except IntegrityError:   # 有错误报出来，就回滚
                db.session.rollback()


class Permission:
    FOLLOW = 0x01  # 关注权限
    COMMIT = 0x02  # 在他人撰写的博文中发布评论
    WRITE_ARTICLES = 0x40  # 写原创博文权限
    MODERATE_COMMENTS = 0x80  # 查处他人发表的不当言论
    ADMINISTER = 0xff  # 管理网站
    # 对应permission 的值 就是16进制的上面的值相加 然后转换成10进制在数据库中的显示


@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))  # get 打成set，纯憨逼


class AnonymousUser(AnonymousUserMixin):
    def can(self, permissions):
        return False

    def is_administrator(self):
        return False


class PostType(db.Model):
    __tablename__ = 'post_types'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True, index=True)
    posts = db.relationship('Post', backref='post_type', lazy='dynamic')
    ceate_id = db.Column(db.Integer, db.ForeignKey(
        'users.id'))
    create_at = db.Column(db.DateTime(), default=datetime.utcnow)
    explain = db.Column(db.String(255), index=True)


login_manager.anonymous_user = AnonymousUser


class Post(db.Model):
    __searchable__ = ['title', 'content']
    __tablename__ = 'posts'
    __analyzer__ = ChineseAnalyzer()

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(256))
    content = db.Column(db.Text)
    content_html = db.Column(db.Text)
    content_text = db.Column(db.Text)
    timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
    last_timestamp = db.Column(
        db.DateTime, default=datetime.utcnow)
    author_id = db.Column(db.Integer, db.ForeignKey(
        'users.id'))  # 按照数据库的写法，表名.字段名
    posttype_id = db.Column(db.Integer, db.ForeignKey(
        'post_types.id'))

    @staticmethod
    def genrate_fake(count=100):
        from random import randint, seed
        import forgery_py

        seed()
        user_count = User.query.count()
        for i in range(count):
            u = User.query.offset(randint(0, user_count - 1)).first()
            p = Post(title=forgery_py.lorem_ipsum.sentences(randint(1, 3)),
                     content=forgery_py.lorem_ipsum.sentences(randint(1, 3)),
                     timestamp=forgery_py.date.date(True),
                     author=u
                     )
            db.session.add(p)
            db.session.commit()

    @staticmethod
    def on_changed_body(target, value, oldvalue, initiator):
        allowed_tags = ['a', 'abbr', 'acronym', 'b', 'blockquote', 'code',
                        'em', 'i', 'li', 'ol', 'pre', 'strong', 'ul',
                        'h1', 'h2', 'h3', 'p']
        content_html = bleach.linkify(bleach.clean(
            markdown(value, output_format='html'), tags=allowed_tags, strip=True))
        text = BeautifulSoup(content_html, 'html.parser')
        target.content_text = text.get_text()
        target.content_text = target.content_text[:200]+"..."
        target.content_text = target.content_text.replace("```", '')
        target.content_text = target.content_text.replace(" ", "")


# flask_whooshalchemyplus.init_app(current_app, Post)
# 全文索引
db.event.listen(Post.content, 'set', Post.on_changed_body)
# 监听数据库 set body
